﻿using System.Security.Cryptography;
using System.Text;
using System.Web;
using InhollandAir.auxiliary;

namespace InhollandAir
{
    public class CryptoRandom
    {
        public static string GetUniqueKey(int maxSize)
        {
            Logging.LogEvent(0, HttpContext.Current.Request.Url, "Unique key generated with max size of " + maxSize, string.Empty, false);

            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            var data = new byte[1];
            var crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            var result = new StringBuilder(maxSize);
            foreach (byte b in data)
                result.Append(chars[b%(chars.Length)]);
            return result.ToString();
        }

        public static string GetIterationCount()
        {
            Logging.LogEvent(0, HttpContext.Current.Request.Url, "Iteration count generated.", string.Empty, false);

            const int maxSize = 5; // Up to 99999
            var chars = "1234567890".ToCharArray();
            var data = new byte[1];
            var crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            var result = new StringBuilder(maxSize);
            foreach (byte b in data)
                result.Append(chars[b%(chars.Length)]);
            return result.ToString();
        }

        public static string GetPaymentReference()
        {
            Logging.LogEvent(0, HttpContext.Current.Request.Url, "Payment reference generated.", string.Empty, false);

            const int maxSize = 8; //Payment references are entered in a comment field...so usually not much longer
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            var data = new byte[1];
            var crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            var result = new StringBuilder(maxSize);
            foreach (byte b in data)
                result.Append(chars[b % (chars.Length)]);
            return result.ToString();
        }
    }
}